<template>
  <div>
    <h2>员工列表</h2>
    <input type="text" v-model="keyword" />
    <button @click="search">搜索</button>
    <table>
      <tr>
        <td>id</td>
        <td>员工名称</td>
        <td>部门名称</td>
        <td>操作</td>
      </tr>

      <tr v-for="i in users" :key="i.id">
        <td>{{i.id}}</td>
        <td>{{i.username}}</td>
        <td>{{i.departname}}</td>
        <td>
          <button>删除</button>
        </td>
      </tr>
    </table>
    <button v-if="previous" @click="pagx(p-1)">上一页</button>
    <button v-for="i in page" :key="i" @click="pagx(i)" :class="i==p?'active':''">{{i}}</button>
    <button v-if="next" @click="pagx(p+1)">下一页</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      users: [],
      page: [],
      p: 1,
      previous: false,
      next: false,
      keyword: ""
    };
  },
  mounted() {
    this.common();
  },
  methods: {
    common() {
      this.axios({
        url: "http://127.0.0.1:8000/app01/user/",
        method: "get",
        params: { p: this.p, keyword: this.keyword }
      }).then(res => {
        this.users = res.data.data.data;
        this.page = res.data.data.page;
        this.previous = res.data.data.previous;
        this.next = res.data.data.next;
      });
    },
    pagx: function(p) {
      this.p = p;
      this.common();
    },
    search: function() {
      this.p = 1;
      this.common();
    }
  }
};
</script>

<style>
table {
  margin: 20px auto;
}
.active {
  background: green;
  color: #fff;
}
</style>